<template>
	<view class="calendar">
		<view class="date flex align-center justify-between font-weight-bold">
			<view class="btns">
				<view class="btn left" @click="changeSwiper('subtract')">
					<text class="iconfont icon-chevron-left font-size-40"></text>
				</view>
			</view>
			<view class="" @click="resetDate">
				<text v-if="calendarList.length"
					class="font-size-32 line-height-46 black-color">{{calendarList[current].year}}年{{calendarList[current].month}}月</text>
			</view>
			<view class="btns">
				<view class="btn" @click="changeSwiper('add')">
					<text class="iconfont icon-chevron-left font-size-40"></text>
				</view>
			</view>
		</view>
		<view class="border-box weeks-wrap">
			<view class="weeks flex align-center">
				<block v-for="(item, index) in weeks">
					<view class="week-item" :key="index">
						<text>{{ item }}</text>
					</view>
				</block>
			</view>
		</view>
		<view class="days">
			<view v-if="calendarList.length" class="swiper-item">
				<view class="flex align-center flex-wrap">
					<block v-for="(item, index) in calendarList[current].list">
						<view :id="'day'+index" class="day-item flex align-center justify-center"
							:class="{
								'black-color': calendarList[current].month === item.month,
								'interval-item-bg': intervalArr.includes(item.date), 
							}" :key="index"
							@click="changeDay(item, calendarList[current].month === item.month, index)">
							<view class="flex align-center justify-center interval-bg-color"
								:class="{
									'interval-bg-color_first-child': intervalArr[0] === item.date, 
									'interval-bg-color_last-child': intervalArr[intervalArr.length - 1] === item.date, 
									'day-active1': (currentDate === item.date && type === 'interval') || (type !== 'interval' && daysarr[item.date]), 
									'active-bg-img': currentDate === item.date && calendarList[current].month === item.month, 
									'has-item-day' : daysarr[item.date] && showDayList && (activityDate === item.date)
									}">
								<text class="font-size-34">{{ item.day }}</text>
							</view>
							<view v-if="daysarr[item.date]" class="flex align-center justify-center"
								:class="{'day-active2': daysarr[item.date]}">
								<text class="font-size-20 line-height-28 text-white">{{ daysarr[item.date] }}场</text>
							</view>
						</view>
					</block>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		name: "com-calendar",
		props: {
			type: {
				type: String,
				default: ''
			},
			start: {
				type: String,
				default: ''
			},
			end: {
				type: String,
				default: ''
			},
			activeDaysArr: {
				type: [Object, Array],
				default: ()=> {}
			}
		},
		data() {
			return {
				weeks: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
				calendarList: [], // 日历
				currentDate: '', // 今天日期
				current: 0, // 当前月份
				currentYear: 0, // 当前年份
				activeList: [], // 暂时没有什么用，后期可删除
				dayLists: [], // 某天的列表数据
				daysarr: {
					// '2024-01-15': 4
				}, // 有数据的日期列表
				toparr: [], // 推荐活动
				nostartarr: [], // 未开始活动
				isendarr: [], // 已完成活动
				location: { // 某天的列表显示位置
					top: 0,
					let: 0
				},
				showDayList: false, // 显示某天的列表
				params: {
					year: '',
					month: '',
					day: '',
				},
				loading: true,
				lists: [],
				scrollTop: 0,
				activityDate: '',
				
				// 区间
				start_interval: '',	// 开始区间
				end_interval: '',	// 结束区间
				intervalArr: [], // 区间激活
			};
		},
		computed: {
			start_end() {
				return {
					start: this.start,
					end: this.end
				}
			}
		},
		watch: {
			start_end: {
				deep: true,
				handler(val) {
					this.start_interval = this.start
					this.end_interval = this.end
					this.init()
				}
			},
			activeDaysArr() {
				this.daysarr = this.activeDaysArr
			}
		},
		mounted() {
			// 获取日历时间
			let date = new Date()
			this.currentDate = this.$formatTime(date, 'YYYY-MM-DD')
			this.currentYear = date.getFullYear()
			this.current = date.getMonth()
			this.params.year = date.getFullYear()
			this.params.month = date.getMonth() + 1
			this.getCalendarList('fist')
			if (this.current === 0) {
				this.current = this.current + 12
				this.getCalendarList('pre')
			} else if (this.current === 11) {
				this.getCalendarList('next')
			}
			
			this.start_interval = this.start
			this.end_interval = this.end
			this.init()
		},
		methods: {
			// 初始化
			init() {
				let start_timestamp = 0
				let end_timestamp = 0
				
				if (this.start_interval, this.end_interval) {
					start_timestamp = new Date(this.start_interval).getTime();
					end_timestamp = new Date(this.end_interval).getTime();
				}
				
				let datesInRange = [];
				
				if (start_timestamp && end_timestamp) {
					let date = ''
					if (start_timestamp > end_timestamp) {
						date = this.start_interval
						this.start_interval = this.end_interval
						this.end_interval = date
					}
					
					let startDate = this.$dayjs(this.start_interval);
					let endDate = this.$dayjs(this.end_interval);
				
					datesInRange.push(this.start_interval)
					let dateStr = startDate.add(1, 'day').format('YYYY-MM-DD');
					
					while (this.$dayjs(dateStr).isBetween(this.start_interval, this.end_interval)) {
						startDate = startDate.add(1, 'day');
						dateStr = startDate.format('YYYY-MM-DD');
						datesInRange.push(dateStr)
					}
					
					if (!datesInRange.includes(this.start_interval)) {
						datesInRange.push(this.start_interval)
					}
					if (!datesInRange.includes(this.end_interval)) {
						datesInRange.push(this.end_interval)
					}
				} else {
					this.intervalArr = [this.start_interval]
				}
				if (datesInRange && datesInRange.length) {
					this.intervalArr = datesInRange
				}
				
			},
			// 重置
			reset() {
				if (this.type === 'interval') {
					this.start_interval = ''	// 开始区间
					this.end_interval = ''	// 结束区间
					this.intervalArr = [] // 区间激活
				}
			},
			/** 
			 * 选择日期
			 * @param {Object} item 某天的数据
			 * @param {Object} status 是否是当月
			 * @param {Object} index 某月某天的下标
			 */
			changeDay(item, status, index) {
				if (this.type === 'interval') {
					this.changeInterval(item, status, index);
					this.$emit('change', {
						start: this.start_interval,
						end: this.end_interval,
						interval: this.intervalArr
					})
				} else {
					if (this.daysarr[item.date]) {
						this.$emit('change', item)
					}
				}
			},
			changeInterval(item, status, index) {
				let start_timestamp = 0
				let end_timestamp = 0
				
				if (this.start_interval && this.end_interval) {
					this.start_interval = ''
					this.end_interval = ''
				}
				
				if (this.start_interval) {
					this.end_interval = item.date
					this.init()
				} else {
					this.start_interval = item.date
				}
			},
			// 返回当前时间
			resetDate() {
				const index = this.calendarList.findIndex(item => item.month === this.$formatTime(new Date(), 'MM') && item
					.year == this.$formatTime(new Date(), 'YYYY'))
				this.current = index
				this.params.year = this.calendarList[this.current].year
				this.params.month = this.calendarList[this.current].month
				this.getScheduleList();
				this.getCalendarTables();
			},
			// 切换年份
			changeSwiperYear(type) {
				let current = type === 'pre' ? this.current - 12 : this.current + 12
				let years = this.calendarList.map(item => item.year)
				let year = type === 'pre' ? this.currentYear - 1 : this.currentYear + 1
				if (type === 'pre' && !years.includes(year)) {
					// 没有上一年的时间
					this.getCalendarList('pre')
				} else if (type === 'next' && !years.includes(year)) {
					// 没有下一年的时间
					this.getCalendarList('next')
				} else {
					this.currentYear = this.calendarList[current].year
				}
				this.$nextTick(() => {
					if (current < 0) {
						let nyear = this.currentYear
						let index = this.calendarList.findIndex(item => item.year === nyear && Number(item
							.month) === Number(this.params.month));
						this.params.year = this.calendarList[index].year
						this.params.month = this.calendarList[index].month
						this.current = index
						this.getCalendarTables();
						return
					}
					this.params.year = this.calendarList[current].year
					this.params.month = this.calendarList[current].month
					this.current = current
					this.getCalendarTables();
				})
			},
			// 切换月份
			changeSwiper(type) {
				let current = type === 'add' ? this.current + 1 : this.current - 1
				this.current = current
				let years = this.calendarList.map(item => item.year)
				if (current === 0 && !years.includes(this.currentYear - 1)) {
					this.getCalendarList('pre')
					this.current = current + 12
				} else if (current === this.calendarList.length - 1 && !years.includes(this.currentYear + 1)) {
					this.getCalendarList('next')
					this.current = current
				} else {
					this.current = current
					this.currentYear = this.calendarList[current].year
				}
			
				this.params.year = this.calendarList[this.current].year
				this.params.month = this.calendarList[this.current].month
				// console.log('params', this.params);
				this.$emit('changeMonth', this.params)
				// this.getCalendarTables();
			},
			// 获取日历时间
			getCalendarList(type = 'fist') {
				let year = 0
				if (type === 'fist') {
					year = this.currentYear
				} else if (type === 'pre') {
					year = this.currentYear - 1
				} else if (type === 'next') {
					year = this.currentYear + 1
				}
				this.currentYear = year

				let month = 1
				let lists = []
				for (let i = 1; i <= 12; i++) {
					month = i < 10 ? `0${i}` : `${i}`
					let num = this.$dayjs(`${year}-${month}`).daysInMonth()
					let list = []
					const firstDate = `${year}-${month}-01`
					const first = new Date(firstDate).getDay()

					// 往前插入多少天
					for (let k = first; k > 0; k--) {
						list.push({
							year: this.$dayjs(firstDate).subtract(k, 'day').format('YYYY'),
							month: this.$dayjs(firstDate).subtract(k, 'day').format('MM'),
							day: this.$dayjs(firstDate).subtract(k, 'day').format('DD'),
							date: this.$dayjs(firstDate).subtract(k, 'day').format('YYYY-MM-DD')
						})
					}
					
					
					// 插入月份天数的日期数据
					for (let j = 1; j <= num; j++) {
						list.push({
							year: `${year}`,
							month: `${month}`,
							day: `${j<10 ? `0${j}` : `${j}`}`,
							date: `${year}-${month}-${j<10 ? `0${j}` : `${j}`}`
						})
					}
					
					const lastDate = list[list.length - 1].date
					const last = new Date(lastDate).getDay()
					
					// 往后插入多少天
					let lastNum = 6;
					if (first + num + (6 - last) < 42) {
						lastNum = 6 + (42 - (first + num + (6 - last)))
					}
					for (let k = 1; k <= lastNum - last; k++) {
						list.push({
							year: this.$dayjs(lastDate).add(k, 'day').format('YYYY'),
							month: this.$dayjs(lastDate).add(k, 'day').format('MM'),
							day: this.$dayjs(lastDate).add(k, 'day').format('DD'),
							date: this.$dayjs(lastDate).add(k, 'day').format('YYYY-MM-DD')
						})
					}

					lists.push({
						list: list,
						month: month,
						year: year
					})
				}

				if (type === 'fist') {
					this.calendarList = lists
				} else if (type === 'pre') {
					let newList = lists
					newList.push(...this.calendarList)
					this.calendarList = newList
				} else if (type === 'next') {
					this.calendarList.push(...lists)
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.calendar {
		padding: 32rpx 32rpx 0;
		box-sizing: border-box;
		// border-radius: 0px 0px 14px 14px;
		// box-shadow: 0px 0px 50px 0px rgba(0, 0, 0, 0.07);
		// background: linear-gradient(180deg, #FBF1F1 0%, #FFF 20.21%);

		.btns {
			display: flex;
			align-items: center;
		}

		.btn {
			width: 42rpx;
			height: 42rpx;
			display: flex;
			margin-left: 10rpx;
			align-items: center;
			justify-content: center;

			&:first-child {
				margin-left: 0;
			}

			image {
				width: 100%;
				height: 100%;
			}
		}

		.left {
			transform: rotate(180deg);
		}

		.date {
			padding: 0 10rpx;
			padding-bottom: 26rpx;
		}

		.weeks-wrap {
			// padding: 0 16rpx;
		}

		.weeks {
			border-radius: 16rpx;
			padding: 16rpx 0;
			// background-color: #FFFFFF;
			// box-shadow: 0rpx 0rpx 22rpx rgba(0, 0, 0, 0.03);


			.week-item {
				color: #000000;
				font-weight: 400;
				font-size: 28rpx;
				line-height: 38rpx;
				text-align: center;
				width: calc(100% / 7);
				box-sizing: border-box;
			}
		}

		.has-item-day {
			position: absolute;
			z-index: 9999999;
			color: #FFFFFF !important;
			background-color: #173C8B !important;
		}

		.item-has {
			position: relative;
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.day-item-has {
			position: absolute;
			width: 100%;
			height: 100%;
			border-radius: 50%;
			background-color: red;
		}

		.days {
			padding-top: 16rpx;

			swiper {
				height: 514rpx;
				box-sizing: border-box;
			}

			.swiper-item {
				// padding: 0 16rpx;
				box-sizing: border-box;
				display: flex;
				justify-content: center;
			}

			.day-item {
				position: relative;
				width: calc(100% / 7);
				height: 92rpx;
				color: rgba(0, 0, 0, 0.2);
				box-sizing: border-box;
				display: flex;
				align-items: center;
				justify-content: center;

				&:nth-child(7n) {
					margin-right: 0;
				}

				.day-active1 {
					width: 68rpx;
					height: 68rpx;
					color: var(--primary-color);
					border-radius: 50%;
					background-color: rgba(226, 46, 46, 0.1);
				}

				.day-active2 {
					position: absolute;
					left: 50%;
					right: 0;
					bottom: -10rpx;
					width: 68rpx;
					height: 34rpx;
					color: #FFFFFF;
					border-radius: 100rpx;
					background: linear-gradient(128deg, #A752FF 59.1%, #00EAFF 111.11%);
					transform: translateX(-50%);
				}

			}
			
			.active-bg-img {
				width: 68rpx;
				height: 68rpx;
				color: var(--primary-color) !important;
				border-radius: 50%;
				background-color: var(--primary-color);
			}
			
			// 区间选中样式
			.day-item.interval-item-bg {
				
				.interval-bg-color {
					width: 68rpx;
					height: 68rpx;
					color: #FFFFFF;
					border-radius: 50%;
					background-color: rgba(226, 46, 46, 0.1);
				}
				
				.interval-bg-color_first-child,
				.interval-bg-color_last-child {
					color: #FFFFFF;
					background-color: var(--primary-color);
				}
			}
		}
		
	}
</style>